package org.csu.onlineedubackend.mapper;

import org.apache.ibatis.annotations.*;
import org.csu.onlineedubackend.entity.GroupMute;

import java.util.Date;
import java.util.List;

@Mapper
public interface GroupMuteMapper {
    
    @Insert("INSERT INTO group_mutes (group_id, user_id, muted_by, mute_until, created_at) " +
            "VALUES (#{groupId}, #{userId}, #{mutedBy}, #{muteUntil}, NOW())")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insert(GroupMute groupMute);
    
    @Select("SELECT * FROM group_mutes WHERE id = #{id}")
    GroupMute findById(Long id);
    
    @Select("SELECT * FROM group_mutes WHERE group_id = #{groupId} AND user_id = #{userId} " +
            "AND (mute_until IS NULL OR mute_until > NOW()) " +
            "ORDER BY created_at DESC LIMIT 1")
    GroupMute findActiveByGroupAndUser(@Param("groupId") Long groupId, @Param("userId") Integer userId);
    
    @Select("SELECT * FROM group_mutes WHERE group_id = #{groupId} AND user_id IS NULL " +
            "AND (mute_until IS NULL OR mute_until > NOW()) " +
            "ORDER BY created_at DESC LIMIT 1")
    GroupMute findActiveGroupMute(Long groupId);
    
    @Select("SELECT * FROM group_mutes WHERE group_id = #{groupId} " +
            "AND (mute_until IS NULL OR mute_until > NOW())")
    List<GroupMute> findActiveByGroupId(Long groupId);
    
    @Update("UPDATE group_mutes SET mute_until = NOW() WHERE id = #{id}")
    int unmute(Long id);
    
    @Update("UPDATE group_mutes SET mute_until = NOW() " +
            "WHERE group_id = #{groupId} AND user_id = #{userId} " +
            "AND (mute_until IS NULL OR mute_until > NOW())")
    int unmuteUser(@Param("groupId") Long groupId, @Param("userId") Integer userId);
    
    @Update("UPDATE group_mutes SET mute_until = NOW() " +
            "WHERE group_id = #{groupId} AND user_id IS NULL " +
            "AND (mute_until IS NULL OR mute_until > NOW())")
    int unmuteGroup(Long groupId);
    
    @Select("SELECT COUNT(*) > 0 FROM group_mutes " +
            "WHERE group_id = #{groupId} AND user_id = #{userId} " +
            "AND (mute_until IS NULL OR mute_until > NOW())")
    boolean isUserMuted(@Param("groupId") Long groupId, @Param("userId") Integer userId);
    
    @Select("SELECT COUNT(*) > 0 FROM group_mutes " +
            "WHERE group_id = #{groupId} AND user_id IS NULL " +
            "AND (mute_until IS NULL OR mute_until > NOW())")
    boolean isGroupMuted(Long groupId);

    @Delete("DELETE FROM group_mutes WHERE group_id = #{groupId}")
    int deleteByGroupId(Long groupId);
} 